import 'dart:convert';

// 构建模式枚举
enum BuildMode {
  standalone('standalone', '独立可执行文件'),
  onefile('onefile', '单文件可执行文件'),
  module('module', '扩展模块');

  const BuildMode(this.value, this.displayName);
  final String value;
  final String displayName;
}

// 优化级别枚举
enum OptimizationLevel {
  none('none', '无优化'),
  basic('basic', '基础优化'),
  advanced('advanced', '高级优化');

  const OptimizationLevel(this.value, this.displayName);
  final String value;
  final String displayName;
}

// 统一配置类
class UnifiedConfig {
  // ============ 项目基本信息 ============
  String? projectPath; // Python主文件路径
  String? projectName; // 项目名称
  String? version; // 版本号
  String? company; // 公司/作者
  String? description; // 项目描述

  // ============ 输出设置 ============
  String? outputDir; // 输出目录
  String? outputFilename; // 输出文件名
  String? iconPath; // 图标路径

  // ============ 构建配置 ============
  BuildMode buildMode; // 构建模式
  OptimizationLevel optimization; // 优化级别
  bool enableLto; // 启用LTO优化
  bool removeAsserts; // 移除断言

  // ============ 调试设置 ============
  bool enableDebug; // 启用调试信息
  bool verbose; // 详细输出
  bool showProgress; // 显示进度

  // ============ 平台设置 ============
  bool disableConsole; // 禁用控制台
  bool enablePlugins; // 启用插件
  bool followImports; // 跟随导入

  // ============ 依赖管理 ============
  List<String> includedModules; // 包含的模块
  List<String> excludedModules; // 排除的模块
  List<String> customDependencies; // 自定义依赖

  // ============ 高级选项 ============
  List<String> extraArgs; // 额外参数
  Map<String, String> environment; // 环境变量

  UnifiedConfig({
    this.projectPath,
    this.projectName,
    this.version,
    this.company,
    this.description,
    this.outputDir,
    this.outputFilename,
    this.iconPath,
    this.buildMode = BuildMode.standalone,
    this.optimization = OptimizationLevel.basic,
    this.enableLto = false,
    this.removeAsserts = false,
    this.enableDebug = false,
    this.verbose = false,
    this.showProgress = true,
    this.disableConsole = false,
    this.enablePlugins = true,
    this.followImports = true,
    List<String>? includedModules,
    List<String>? excludedModules,
    List<String>? customDependencies,
    List<String>? extraArgs,
    Map<String, String>? environment,
  }) : includedModules = includedModules ?? [],
       excludedModules = excludedModules ?? [],
       customDependencies = customDependencies ?? [],
       extraArgs = extraArgs ?? [],
       environment = environment ?? {};

  // 生成Nuitka命令行
  String generateNuitkaCommand() {
    if (projectPath == null || projectPath!.isEmpty) {
      return '';
    }

    List<String> args = ['nuitka'];

    // 构建模式
    switch (buildMode) {
      case BuildMode.standalone:
        args.add('--standalone');
        break;
      case BuildMode.onefile:
        args.add('--onefile');
        break;
      case BuildMode.module:
        args.add('--module');
        break;
    }

    // 优化设置
    switch (optimization) {
      case OptimizationLevel.none:
        args.add('--no-optimization');
        break;
      case OptimizationLevel.basic:
        // 默认优化，不需要特殊参数
        break;
      case OptimizationLevel.advanced:
        // 高级优化，移除无效参数
        break;
    }

    if (enableLto || optimization == OptimizationLevel.advanced) {
      args.add('--lto=yes');
    }

    if (removeAsserts) {
      args.add('--remove-output');
    }

    // 调试设置
    if (enableDebug) {
      args.add('--debug');
    }

    if (verbose) {
      args.add('--verbose');
    }

    if (showProgress) {
      args.add('--show-progress');
    }

    // 平台设置
    if (disableConsole) {
      args.add('--disable-console');
    }

    // 使用Nuitka 2.7.12有效的插件
    if (enablePlugins) {
      args.add('--enable-plugin=tk-inter');
      args.add('--enable-plugin=numpy');
      args.add('--enable-plugin=multiprocessing');
      args.add('--enable-plugin=anti-bloat');
    }

    if (followImports) {
      args.add('--follow-imports');
    }

    // 输出设置
    if (outputDir != null && outputDir!.isNotEmpty) {
      args.add('--output-dir=\"$outputDir\"');
    }

    if (outputFilename != null && outputFilename!.isNotEmpty) {
      args.add('--output-filename=\"$outputFilename\"');
    }

    if (iconPath != null && iconPath!.isNotEmpty) {
      args.add('--windows-icon-from-ico=\"$iconPath\"');
    }

    // 包含模块
    for (String module in includedModules) {
      args.add('--include-module=$module');
    }

    // 排除模块
    for (String module in excludedModules) {
      args.add('--nofollow-import-to=$module');
    }

    // 自定义依赖
    for (String dep in customDependencies) {
      args.add('--include-package=$dep');
    }

    // 额外参数
    args.addAll(extraArgs);

    // Python文件路径
    args.add('\"$projectPath\"');

    return args.join(' ');
  }

  // JSON序列化
  // 生成nuitka命令
  String generateCommand() {
    final args = <String>['nuitka'];

    // 构建模式
    switch (buildMode) {
      case BuildMode.onefile:
        args.add('--onefile');
        break;
      case BuildMode.standalone:
        args.add('--standalone');
        break;
      case BuildMode.module:
        args.add('--module');
        break;
    }

    // 优化级别
    switch (optimization) {
      case OptimizationLevel.none:
        args.add('--no-optimization');
        break;
      case OptimizationLevel.basic:
        // 基础优化，不添加额外参数
        break;
      case OptimizationLevel.advanced:
        if (enableLto) args.add('--lto=yes');
        break;
    }

    // 其他选项
    if (showProgress) args.add('--show-progress');
    if (disableConsole) args.add('--disable-console');
    if (followImports) args.add('--follow-imports');

    // 插件
    if (enablePlugins) {
      args.addAll([
        '--enable-plugin=tk-inter',
        '--enable-plugin=numpy',
        '--enable-plugin=multiprocessing',
        '--enable-plugin=anti-bloat',
      ]);
    }

    // 输出目录
    if (outputDir?.isNotEmpty == true) {
      args.add('--output-dir=$outputDir');
    }

    // 输出文件名
    if (outputFilename?.isNotEmpty == true) {
      args.add('--output-filename=$outputFilename');
    }

    // Python文件路径 - 这是最关键的部分，必须存在！
    if (projectPath?.isNotEmpty == true) {
      args.add(projectPath!);
    } else {
      // 如果没有项目路径，返回错误提示而不是空命令
      return 'ERROR: 请先选择要编译的Python文件！';
    }

    return args.join(' ');
  }

  Map<String, dynamic> toJson() {
    return {
      'projectPath': projectPath,
      'projectName': projectName,
      'version': version,
      'company': company,
      'description': description,
      'outputDir': outputDir,
      'outputFilename': outputFilename,
      'iconPath': iconPath,
      'buildMode': buildMode.value,
      'optimization': optimization.value,
      'enableLto': enableLto,
      'removeAsserts': removeAsserts,
      'enableDebug': enableDebug,
      'verbose': verbose,
      'showProgress': showProgress,
      'disableConsole': disableConsole,
      'enablePlugins': enablePlugins,
      'followImports': followImports,
      'includedModules': includedModules,
      'excludedModules': excludedModules,
      'customDependencies': customDependencies,
      'extraArgs': extraArgs,
      'environment': environment,
    };
  }

  // JSON反序列化
  factory UnifiedConfig.fromJson(Map<String, dynamic> json) {
    return UnifiedConfig(
      projectPath: json['projectPath'],
      projectName: json['projectName'],
      version: json['version'],
      company: json['company'],
      description: json['description'],
      outputDir: json['outputDir'],
      outputFilename: json['outputFilename'],
      iconPath: json['iconPath'],
      buildMode: BuildMode.values.firstWhere(
        (mode) => mode.value == json['buildMode'],
        orElse: () => BuildMode.standalone,
      ),
      optimization: OptimizationLevel.values.firstWhere(
        (level) => level.value == json['optimization'],
        orElse: () => OptimizationLevel.basic,
      ),
      enableLto: json['enableLto'] ?? false,
      removeAsserts: json['removeAsserts'] ?? false,
      enableDebug: json['enableDebug'] ?? false,
      verbose: json['verbose'] ?? false,
      showProgress: json['showProgress'] ?? true,
      disableConsole: json['disableConsole'] ?? false,
      enablePlugins: json['enablePlugins'] ?? true,
      followImports: json['followImports'] ?? true,
      includedModules: List<String>.from(json['includedModules'] ?? []),
      excludedModules: List<String>.from(json['excludedModules'] ?? []),
      customDependencies: List<String>.from(json['customDependencies'] ?? []),
      extraArgs: List<String>.from(json['extraArgs'] ?? []),
      environment: Map<String, String>.from(json['environment'] ?? {}),
    );
  }

  // 复制配置
  UnifiedConfig copyWith({
    String? projectPath,
    String? projectName,
    String? version,
    String? company,
    String? description,
    String? outputDir,
    String? outputFilename,
    String? iconPath,
    BuildMode? buildMode,
    OptimizationLevel? optimization,
    bool? enableLto,
    bool? removeAsserts,
    bool? enableDebug,
    bool? verbose,
    bool? showProgress,
    bool? disableConsole,
    bool? enablePlugins,
    bool? followImports,
    List<String>? includedModules,
    List<String>? excludedModules,
    List<String>? customDependencies,
    List<String>? extraArgs,
    Map<String, String>? environment,
  }) {
    return UnifiedConfig(
      projectPath: projectPath ?? this.projectPath,
      projectName: projectName ?? this.projectName,
      version: version ?? this.version,
      company: company ?? this.company,
      description: description ?? this.description,
      outputDir: outputDir ?? this.outputDir,
      outputFilename: outputFilename ?? this.outputFilename,
      iconPath: iconPath ?? this.iconPath,
      buildMode: buildMode ?? this.buildMode,
      optimization: optimization ?? this.optimization,
      enableLto: enableLto ?? this.enableLto,
      removeAsserts: removeAsserts ?? this.removeAsserts,
      enableDebug: enableDebug ?? this.enableDebug,
      verbose: verbose ?? this.verbose,
      showProgress: showProgress ?? this.showProgress,
      disableConsole: disableConsole ?? this.disableConsole,
      enablePlugins: enablePlugins ?? this.enablePlugins,
      followImports: followImports ?? this.followImports,
      includedModules: includedModules ?? this.includedModules,
      excludedModules: excludedModules ?? this.excludedModules,
      customDependencies: customDependencies ?? this.customDependencies,
      extraArgs: extraArgs ?? this.extraArgs,
      environment: environment ?? this.environment,
    );
  }
}
